package com.pzhu.servlet;

import com.pzhu.service.UserService;
import com.pzhu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class MainServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        1.设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
//        2.获取cookie
        if (req.getCookies() == null) { //为空时请求转发到page登录界面
            req.getRequestDispatcher("view/jsp/login.jsp").forward(req, resp);
            System.out.println("cookie 为空 跳转登录界面");
            return;//请求转发之后需要return
        }
        for (Cookie reqCookie : req.getCookies()) {
            if ("Uid".equals(reqCookie.getName())) {  //判断是否有id的cookie
                if ("".equals(reqCookie.getValue())) {     //获取cookie的id
                    req.getRequestDispatcher("/library/view/jsp/login.jsp").forward(req, resp);
                    System.out.println("cookie 不含登录信息 跳转登录界面");
                    return;//请求转发之后需要return
                }
                System.out.println(reqCookie.getValue());
                //查询cookie数据是否在数据库中
                if (userService.checkUserById(Integer.parseInt(reqCookie.getValue()))) {
//                    重置cookie TTL
                    System.out.println("查询cookie成功");
                    Cookie cookie = new Cookie("Uid", reqCookie.getValue());
                    cookie.setMaxAge(7 * 24 * 3600);//设置生存时间 单位 /秒
                    cookie.setPath("/library/main");//生效路径
//                  添加进resp，返回浏览器
                    resp.addCookie(cookie);
//                   添加session
                    int id = Integer.parseInt(cookie.getValue());
                    HttpSession session = req.getSession();
                    session.setMaxInactiveInterval(1 * 1 * 3600);//设置生存时间 单位 /秒
                    System.out.println(userService.selectUserById(id));
                    session.setAttribute("login",true);
                    session.setAttribute("Uid", id);
                    session.setAttribute("Uname", userService.selectUserById(id).getName());
                    req.getRequestDispatcher("/show-all-books").forward(req, resp);
                    System.out.println("cookie 通过 跳转到首页");
                    return;//重定向之后return
                } else {
                    req.getRequestDispatcher("view/jsp/login.jsp").forward(req, resp);
                    System.out.println("cookie 存储信息验证不通过 跳转登陆页面");
                    return;
                }
            }
        }
//        当遍历完cookie仍没有正确的数据，请求转发登录页面
        req.getRequestDispatcher("view/jsp/login.jsp").forward(req, resp);
        return;
    }
}